import {
    createSlice,
    createAsyncThunk, //创建异步thunk
    PayloadAction
} from '@reduxjs/toolkit';
import { login } from '../../api/user';
import { ILoginForm } from '../../interface/user';
import { Toast } from 'antd-mobile';
import { UserInfo } from '../../types/user';
/**
 * createAsyncThunk 管理异步方法或任务
 * 参数1 可以理解为一个签名
 * 参数2 是 thunk 暴露的 api
 */
export const userLogin = createAsyncThunk('user/userLogin', async (params: ILoginForm, { dispatch }) => {
    return new Promise<any>(async (resolve, reject) => {
        try {
            const res = await login(params);
            if (res.data.code === 200) {
                // 派发 reduce
                dispatch(setUserInfo(res.data));
                resolve(res.data);
            }
        } catch (error: any) {
            Toast.show(error);
            reject(error);
        }
    });
});
/**
 * createSlice 编写 reducers
 * name 签名
 * initialState 初始值
 * reducers reduce 逻辑方法
 */
const userSlice = createSlice({
    name: 'user',
    initialState: {
        userInfo: {} as UserInfo
    },
    reducers: {
        setUserInfo: (state, action: PayloadAction<any>) => {
            state.userInfo = action.payload;
        }
    }
});
export const { setUserInfo } = userSlice.actions;
// 默认导出 reducer
export default userSlice;
